﻿using System;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Higgs.Web.AtomPub.ActionResults;

namespace Higgs.Web.AtomPub.Attributes
{
    public class AtomAuthroizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // Require basic authentication for access.
            var authorizeHeader = httpContext.Request.Headers["Authorization"];
            if (string.IsNullOrEmpty(authorizeHeader) || !authorizeHeader.StartsWith("basic ", StringComparison.InvariantCultureIgnoreCase))
            {
                return false;
            }

            authorizeHeader = Encoding.ASCII.GetString(Convert.FromBase64String(authorizeHeader.Substring(6)));
            var loginData = authorizeHeader.Split(':');
            httpContext.User = AuthenticaterMethod(httpContext, loginData[0], loginData[1]);
            httpContext.Response.Expires = -1;

            return httpContext.User != null && httpContext.User.Identity.IsAuthenticated;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
        {
            filterContext.Result = new UnauthorizedResult();
        } 

        protected static Func<HttpContextBase, string, string, IPrincipal> AuthenticaterMethod = (context, loginName, password) => new BasicPrincipal(loginName);
        public static void RegisterAuthenticater(Func<HttpContextBase, string, string, IPrincipal> method)
        {
            AuthenticaterMethod = method;
        }
    }
}